/**
 * 
 */
(function() {
	/***************************************************************************
	 * 列表页面初始方法
	 */
	//	document.onkeydown = function(e) {
	//		platform.forbiddenEnter(e);
	//	}
	window.onload = function() {
		roleGridView.init();
    };
	/***************************************************************************
	 * 元件绑定
	 */
	var roleGridView = {
		/**
		 * Method
		 */
		init: function() {
			var columns = [{
				checkbox: true,
				field: 'checkbox',
				align: 'center',
				valign: 'middle'
			}, {
				field: 'role_id',
				title: '主键标识',
				width: 250,
				valign: 'middle',
				align: 'center'
			}, {
				field: 'role_name',
				title: '角色名称',
				width: 120,
				valign: 'middle'
			}, {
				field: 'role_code',
				title: '角色编码',
				width: 200,
				valign: 'middle'
			}, {
				field: 'def_uri',
				title: '默认主页地址',
				width: 200,
				valign: 'left'
			}];
			$('#tb_roles').bootstrapTable({
				url: platform.mapUrl('~/rest/role/list'),
				cache: false,
				method: 'post',
				contentType: 'application/json',
				dataType: 'json',
				search: false,
				strictSearch: true,
				singleSelect: true,
				striped: true,
				showFooter: false,
				showToggle: false,
				showRefresh: true,
				showPaginationSwitch: false,
				silent: true,
				pagination: true,
				sidePagination: 'server',
				pageNumber: 1,
				pageSize: 10,
				pageList: [10, 15, 20, 50],
				queryParams: function(params) {
					return {
						pageNumber: params.offset / params.limit + 1,
						pageSize: params.limit
					}
				},
				clickToSelect: true,
				height: 504,
				uniqueId: 'role_id',
				roleView: false,
				cardView: false,
				toolbar: '#toolbar',
				columns: columns
			}).bootstrapTable('hideColumn', 'role_id');
		},
		fnSearch: function() {
			$("#tb_roles").bootstrapTable("refresh", {
				query: {
					role_name: $("#name").val() == "" ? null : $("#name").val()
				}
			});
		},
		fnAdd: function() {
			roleViewHeader.rv_title('权限信息录入');
			roleView.clear();
			roleView.initForm();
			roleView.validateForm();
			$('#roleViewModal').modal('show');
		},
		fnRemove: function() {
			var result = platform.checkSelected('tb_roles', 'remove');
			if(result) {
				platform.confirm(
					'系统提示',
					'small',
					'删除角色将解除角色与用户、权限、菜单关系,确认是否执行?',
					'确认',
					'取消',
					function() {
						var role_id = platform
							.getSelected('tb_roles')[0].role_id;
						methods.del(role_id);
					});
			}
		},
		fnEdit: function() {
			// platform.showtip('EDIT');
		},
		fnView: function() {
			// platform.showtip('VIEW');
		},
		fnGrantMenu: function() {
			// grantMenuView.show();
			var result = platform.checkSelected('tb_roles', 'grant');
			if(result) {
				var role_id = platform.getSelected('tb_roles')[0].role_id;
				grantMenuView.gtm_title('菜单选择');
				grantMenuView.show(role_id);
			}
		},
		fnGrantUser: function() {
			var result = platform.checkSelected('tb_roles', 'grant');
			if(result) {
				var role_id = platform.getSelected('tb_roles')[0].role_id;
				grantUserView.gtg_title('用户选择');
				grantUserView.show(role_id);
			}
		},
		fnGrantPerm: function() {
			var result = platform.checkSelected('tb_roles', 'grant');
			if(result) {
				var role_id = platform.getSelected('tb_roles')[0].role_id;
				grantPermView.gtg_title('权限选择');
				grantPermView.show(role_id);
			}
		}
	};
	ko.applyBindings(roleGridView, document.getElementById('roleGridView'));
	/***************************************************************************
	 * roleViewHeader
	 */
	var roleViewHeader = {
		rv_title: ko.observable()
    };
	ko.applyBindings(roleViewHeader, document.getElementById('modalHeader'));
	/***************************************************************************
	 * roleView
	 */
	var roleView = {
		rv_roleid: ko.observable(), // 角色ID
		rv_rolename: ko.observable(), // 角色名称
		rv_rolecode: ko.observable(), // 角色编码
		rv_rolegroudid: ko.observable(), // 角色组，暂未实现20170320
		rv_defuri: ko.observable(), // 默认首页
		rv_editstatus: ko.observable(), // 默认数据状态
		rv_recordstatus: ko.observable(), // 默认数据状态
		rv_enabled: ko.observable(false), // 只读设置
		/**
		 * method
		 */
		initForm: function() {
			this.rv_roleid(platform.uuid());
			this.rv_editstatus('0');
			this.rv_recordstatus('1');
			this.rv_enabled(true);
		},
		clear: function() {
			this.rv_roleid('');
			this.rv_rolename('');
			this.rv_rolecode('');
			this.rv_defuri('');
			this.rv_editstatus('');
			this.rv_recordstatus('');
			this.rv_enabled(false);
		},
		validateForm: function() {
			$('#roleForm').bootstrapValidator({
				message: 'This value is not valid',
				feedbackIcons: {
					valid: 'glyphicon glyphicon-ok',
					invalid: 'glyphicon glyphicon-remove',
					validating: 'glyphicon glyphicon-refresh'
				},
				excluded: [':disabled'],
				fields: {
					roleName: {
						validators: {
							notEmpty: {
								message: '角色名称为必填字段,不可为空'
							}
						}
					},
					roleCode: {
						validators: {
							notEmpty: {
								message: '角色编码为必填字段,不可为空'
							}
						}
					}
				}
			});
		},
		resetForm: function() {
			if($('#roleForm').data('bootstrapValidator') != null ||
				$('#roleForm').data('bootstrapValidator') != undefined) {
				$('#roleForm').data('bootstrapValidator').resetForm();
			}
		}
    };
	ko.applyBindings(roleView, document.getElementById('roleForm'));
	/***************************************************************************
	 * menuFunctionView
	 */
	var menuFunctionView = {
		fnSaveForm: function() {
			$('#roleForm').data('bootstrapValidator').validate();
			if(!$('#roleForm').data('bootstrapValidator').isValid()) {
				platform.showOperTip('VALIDATEFAIL');
				return;
			}
			var form = roleView;
			var param = {};
			param.role_id = form.rv_roleid();
			param.role_name = form.rv_rolename();
			param.role_code = form.rv_rolecode();
			param.edit_status = form.rv_editstatus();
			param.record_status = form.rv_recordstatus();
			var result = methods.repeatCheck(param.role_code);
			if(result.statusCode) {
				methods.save(param);
			} else {
				platform.showErrorTip(result.msg);

			}
		},
		fnCloseDlg: function() {
			roleView.resetForm();
			$('input', 'form').attr('readonly');
			$('#roleViewModal').modal('hide');
		}
    };
	ko.applyBindings(menuFunctionView, document.getElementById('modalFooter'));
	/***************************************************************************
	 * grantMenuView
	 */
	var selectionMIds = [];
	var grantMenuView = {
		gtm_title: ko.observable(),
		show: function(roleId) {
			var param = {};
			param.role_id = roleId;
			var nodes = methods.loadTreeNodes(param);
			platform.removeEmptyNode(nodes);
			console.log(nodes);
			$tree = $("#grantedTree").treeview({
				data: nodes,
				highlightSelected: true,
				selectable: true,
				emptyIcon: "",
				showCheckbox: true,
				levels: 2
			});

			//			$tree.on('nodeChecked', function(event, node) {
			//				console.log(node);
			//				if (node.pid != '') {
			//					$tree.treeview('checkNode', [ $tree.treeview('getNode',node.pid), {
			//						silent : false
			//					} ]);
			//				}
			//			}).on('nodeUnchecked', function(event, node) {
			//				
			//			});
			$('#grantedMenuModal').modal('show');
		},
		fnDistribute: function() {
			var roleId = platform.getSelected('tb_roles')[0].role_id;
			var checkedItems = $("#grantedTree").treeview('getChecked');
			var menuIds = [];
			$.each(checkedItems, function(index, item) {
				if($.inArray(item.id, menuIds) == -1) {
					menuIds.push(item.id);
				}
			});
			var param = {};
			param.role_id = roleId;
			param.menu_id = menuIds;
			methods.grantMenu(param);
		},
		fnCancel: function() {
			$('#grantedMenuModal').modal('hide');
		}
	};
	ko.applyBindings(grantMenuView, document.getElementById('grantedMenuModal'));
	/***************************************************************************
	 * grantUserView
	 */
	selectionUIds = [];
	var grantUserView = {
		gtg_title: ko.observable(),
		show: function(roleId) {
			var columns = [{
				checkbox: true,
				field: 'checkStatus',
				align: 'center',
				valign: 'middle',
				formatter: function(value, row, index) {
					if(row.checked != 0) {
						if($.inArray(row.user_id, selectionUIds) == -1) {
							// array[array.length] = id;
							selectionUIds.push(row.user_id);
						}
						// selectionUIds.push(row.user_id);
						return {
							checked: true,
						}
					}
				}
			}, {
				field: 'user_id',
				title: '主键标识',
				width: 60,
				valign: 'middle',
				align: 'center',
				visible: false
			}, {
				field: 'user_name',
				title: '用户名',
				width: 120,
				valign: 'middle'
			}, {
				field: 'nick_name',
				title: '显示名称',
				width: 180,
				valign: 'middle'
			}];
			$('#grantedUserGrid').bootstrapTable({
				url: platform.mapUrl('~/rest/role/getUsersByRoleId'),
				cache: false,
				method: 'post',
				contentType: 'application/json',
				dataType: 'json',
				search: false,
				strictSearch: false,
				singleSelect: false,
				striped: true,
				showFooter: false,
				showToggle: false,
				// showRefresh : true,
				showPaginationSwitch: false,
				silent: true,
				pagination: false,
				sidePagination: 'server',
				pageNumber: 1,
				pageSize: 5,
				pageList: [5],
				queryParams: function(params) {
					return {
						//								pageNumber : params.offset / params.limit + 1,
						//								pageSize : params.limit,
						role_id: roleId
					}
				},
				clickToSelect: true,
				height: 275,
				uniqueId: 'user_id',
				detailView: false,
				cardView: false,
				columns: columns,
				responseHandler: function(res) {
					console.log("load:" + selectionUIds);
					$.each(res.rows, function(i, row) {
						row.checkStatus = $.inArray(row.user_id, selectionUIds) != -1;
					});
					return res;
				}
			}).on('page-change.bs.table', function(number, size) {
				console.log('pageChange');
			});

			var _ = {
				"union": union,
				"difference": difference
			};
			$('#grantedUserGrid').on('check.bs.table check-all.bs.table uncheck.bs.table uncheck-all.bs.table',
				function(e, rows) {
					var ids = $.map(!$.isArray(rows) ? [rows] : rows, function(row) {
						return row.user_id;
					});
					func = $.inArray(e.type, ['check', 'check-all']) > -1 ? 'union' : 'difference';
					selectionUIds = _[func](selectionUIds, ids);
				});
			$('#grantedUserGridModal').modal('show');
		},
		fnDistribute: function() {
			var roleId = platform.getSelected('tb_roles')[0].role_id;
			console.log(selectionUIds);
			var param = {};
			param.role_id = roleId;
			param.user_id = selectionUIds;
			console.log(param);
			methods.grantUser(param);
		},
		fnCancel: function() {
			selectionUIds.splice(0, selectionUIds.length);
			selectionUIds = [];
			console.log(selectionUIds);
			$('#grantedUserGrid').bootstrapTable('refreshOptions', {
				pageNumber: 1
			});
			$('#grantedUserGridModal').modal('hide');
		}
	};
	ko.applyBindings(grantUserView, document.getElementById('grantedUserGridModal'));
	/***************************************************************************
	 * grantPermView
	 */
	selectionPIds = [];
	var grantPermView = {
		gtg_title: ko.observable(),
		show: function(roleId) {
			var columns = [{
				checkbox: true,
				field: 'checkbox',
				align: 'center',
				valign: 'middle',
				formatter: function(value, row, index) {
					if(row.checked != 0) {
						selectionPIds.push(row.perm_id);
						return {
							checked: true,
						}
					}
				}
			}, {
				field: 'perm_id',
				title: '主键标识',
				width: 120,
				valign: 'middle',
				align: 'center',
				visible: false
			}, {
				field: 'perm_code',
				title: '权限编码',
				width: 80,
				valign: 'middle'
			}, {
				field: 'perm_name',
				title: '权限名称',
				width: 200,
				valign: 'left'
			}];
			$('#grantedPermGrid').bootstrapTable({
				url: platform.mapUrl('~/rest/role/getPermsByRoleId'),
				cache: false,
				method: 'post',
				contentType: 'application/json',
				dataType: 'json',
				search: false,
				strictSearch: false,
				singleSelect: false,
				striped: true,
				showFooter: false,
				showToggle: false,
				// showRefresh : true,
				showPaginationSwitch: false,
				silent: true,
				pagination: false,
				sidePagination: 'server',
				pageNumber: 1,
				pageSize: 5,
				pageList: [5],
				queryParams: function(params) {
					return {
						//								pageNumber : params.offset / params.limit + 1,
						//								pageSize : params.limit,
						role_id: roleId
					}
				},
				clickToSelect: true,
				height: 260,
				uniqueId: 'perm_id',
				detailView: false,
				cardView: false,
				columns: columns,
				responseHandler: function(res) {
					console.log(selectionPIds);
					$.each(res.rows, function(i, row) {
						row.checkStatus = $.inArray(row.user_id,
							selectionPIds) != -1;
					});
					return res;
				}
			});
			var _ = {
				"union": union,
				"difference": difference
			};
			$('#grantedPermGrid')
				.on(
					'check.bs.table check-all.bs.table uncheck.bs.table uncheck-all.bs.table',
					function(e, rows) {
						var ids = $.map(!$.isArray(rows) ? [rows] :
							rows,
							function(row) {
								return row.perm_id;
							});
						func = $.inArray(e.type, ['check', 'check-all']) > -1 ? 'union' :
							'difference';
						selectionPIds = _[func](selectionPIds, ids);
					});
			$('#grantedPermGridModal').modal('show');
		},
		fnDistribute: function() {
			var roleId = platform.getSelected('tb_roles')[0].role_id;
			console.log(selectionPIds);
			var param = {};
			param.role_id = roleId;
			param.perm_id = selectionPIds;
			methods.grantPerm(param);
		},
		fnCancel: function() {
			selectionPIds.splice(0, selectionPIds.length);
			selectionPIds = [];
			console.log(selectionPIds);
			$('#grantedPermGrid').bootstrapTable('resetView');
			$('#grantedPermGrid').bootstrapTable('refreshOptions', {
				pageNumber: 1
			});
			$('#grantedPermGridModal').modal('hide');
		}
	};
	ko.applyBindings(grantPermView, document.getElementById('grantedPermGridModal'));
	/***************************************************************************
	 * 方法定义
	 */
	// 选中事件操作数组
	var union = function(array, ids) {
		$.each(ids, function(i, id) {
			if($.inArray(id, array) == -1) {
				array[array.length] = id;
			}
		});
		return array;
	};
	// 取消选中事件操作数组
	var difference = function(array, ids) {
		$.each(ids, function(i, id) {
			var index = $.inArray(id, array);
			if(index != -1) {
				array.splice(index, 1);
			}
		});
		return array;
	};
	var methods = {
		repeatCheck: function(roleCode) {
			var param = {};
			param.role_code = roleCode;
			var result = JSON2.parse(platform.servicebreak(
				'~/rest/role/repeatCheck', param).responseText);
			return result;
		},
		del: function(pid) {
			var param = {};
			param.role_id = pid;
			platform.servicebreakAsync('~/rest/role/delete', param, 'post')
				.done(function(response) {
					if(response.success) {
						platform.showOperTip('DELSUC');
						$('#tb_roles').bootstrapTable('refresh');

                    } else {
						plaform.showOperTip('DELFAIL');

                    }
				});
		},
		save: function(param) {
			platform.servicebreakAsync('~/rest/role/save', param, 'post',
				function() {
					platform.showOperTip('dealing');
				}).done(function() {
				platform.showOperTip('savesuc');
				$('#tb_roles').bootstrapTable('refresh');
			});
		},
		loadTreeNodes: function(param) {
			var nodes = JSON2.parse(platform
				.servicebreak('~/rest/role/getMenusByRoleId', param).responseText);
			return nodes;
		},
		grantMenu: function(param) {
			platform.servicebreakAsync('~/rest/role/grantMenuToRole', param,
				'post').done(function(response) {
				if(response.success) {
					platform.showOperTip('GRANTSUC');
				} else {
					platform.showOperTip('GRANTFAIL');
				}
				grantMenuView.fnCancel();
			});
		},
		grantUser: function(param) {
			platform.servicebreakAsync('~/rest/role/grantRoleToUser', param,
				'post').done(function(response) {
				if(response.success) {
					platform.showOperTip('GRANTSUC');
				} else {
					platform.showOperTip('GRANTFAIL');
				}
				grantUserView.fnCancel();
			});
		},
		grantPerm: function(param) {
			platform.servicebreakAsync('~/rest/role/grantPermToRole', param,
				'post').done(function(response) {
				if(response.success) {
					platform.showOperTip('GRANTSUC');
				} else {
					platform.showOperTip('GRANTFAIL');
				}
				grantPermView.fnCancel();
			});
		}
	};
})(this);